<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 管理员角色管理
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: role.php 213 2012-05-24 09:33:22Z yellow.chow $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Controller_Admin_Manager_Role extends Controller_Admin_Base
{

    /**
     * 角色列表
     */
    public function action_index()
    {
        $this->view->roles = Model::factory('manager_role')->all();
    }

    /**
     * 添加角色
     */
    public function action_add()
    {
        $model = Model::factory('manager_role');

        if ($this->request->is_post())
        {
            if ( ! $model->add($this->request->post()))
            {
                $this->view->errors = $model->errors('admin.manager.role');
            }
            $this->render('admin/common/message');
        }
    }

    /**
     * 编辑角色
     */
    public function action_edit()
    {
        $role_id = $this->request->param('id');
        $model = Model::factory('manager_role');
        $role = $model->get($role_id);

        if ( ! $role)
        {
            $this->message('admin.manager.role.not_found')
                ->link(URL::site('admin/manager_role'), 'admin.manager.role.index_url')
                ->render();
        }

        if ($this->request->is_post())
        {
            if ( ! $model->edit($role_id, $this->request->post()))
            {
                $this->view->errors = $model->errors('admin.manager.role');
            }
            $this->render('admin/common/message');
        }

        $this->view->set($role);
    }

    /**
     * 权限指派
     */
    public function action_assign()
    {
        $this->privilege('manager.role.assign');

        $role_id = $this->request->param('id');
        $rule = Model::factory('manager_rule');

        if ($this->request->is_post())
        {
            if ( ! $rule->assign($role_id, (array) $this->request->post('rules')))
            {
                $this->view->errors = $rule->errors('admin.manager.role');
            }
            $this->render('admin/common/message');
        }

        // 权限规则
        $this->view->rules = $rule->all($role_id);

        // 权限列表
        $this->view->privileges = Model::factory('manager_privilege')->all();
    }

    /**
     * 删除角色
     */
    public function action_del()
    {
        $role_id = $this->request->param('id');
        $model = Model::factory('manager_role');

        if ( ! $model->del($role_id))
        {
            $this->view->errors = $model->errors('admin.manager.role');
        }

        $this->render('admin/common/message');
    }

}
